<?php

namespace app\api\model;

use app\admin\model\Crontab;
use app\admin\model\User;
use app\api\model\Carts;

use app\api\model\OrderAction;
use think\Db;
use think\Exception;
use think\Model;

use Yansongda\Pay\Exceptions\GatewayException;
use addons\epay\library\Service;

use traits\model\SoftDelete;

/**
 * 模型
 */
class Order extends Model
{

    use SoftDelete;
    // 表名
    protected $name = 'shop_order';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';
    // 追加属性
    protected $append = [

    ];




    public function getOrderstateList()
    {
        return ['0' => __('Orderstate 0'), '1' => __('Orderstate 1'), '2' => __('Orderstate 2'), '3' => __('Orderstate 3'), '4' => __('Orderstate 4'), '5' => __('Orderstate 5')];
    }

    public function getShippingstateList()
    {
        return ['0' => __('Shippingstate 0'), '1' => __('Shippingstate 1'), '2' => __('Shippingstate 2'), '3' => __('Shippingstate 3')];
    }

    public function getPaystateList()
    {
        return ['0' => __('Paystate 0'), '1' => __('Paystate 1')];
    }

    public function getOrderstateTextAttr($value, $data)
    {
        $value = $value ? $value : $data['orderstate'];
        $list = $this->getOrderstateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getShippingstateTextAttr($value, $data)
    {
        $value = $value ? $value : $data['shippingstate'];
        $list = $this->getShippingstateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getPaystateTextAttr($value, $data)
    {
        $value = $value ? $value : $data['paystate'];
        $list = $this->getPaystateList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getStatusTextAttr($value, $data)
    {
        if ($data['orderstate'] == 0) {
            if ($data['paystate'] == 0) {
                return '待付款';
            }
            if ($data['shippingstate'] == 0) {
                return '待配送';
            } else if ($data['shippingstate'] == 1) {
                return '配送中';
            } else if ($data['shippingstate'] == 2) {
                return '已完成';
            }
        } else if ($data['orderstate'] == 1) {
            return '已取消';
        } else if ($data['orderstate'] == 2) {
            return '已失效';
        }  else if ($data['orderstate'] == 3) {
            if ($data['salestate'] == 4) {
                return '退款成功';
            } else {
                return '已完成';
            }
        } else if ($data['orderstate'] == 4) {
            return '退货/退款中';
        }
        return '未知';
    }

    //获取订单剩余有效时长
    public function getRemainsecondsAttr($value, $data)
    {
        return max(0, $data['expiretime'] - time());
    }

    //计算购物车商品
    public static function computeCarts(&$orderInfo, $cart_ids, $user_id, $user_coupon_id = '',$date,$goods_sku_id)
    {
        $user = User::get($user_id);
        $member_discount = \app\common\model\Config::get(['name'=>'member_discount'])->value;
        $date_arr = Carts::where(['user_id'=>$user_id])
            ->where('id','in',$cart_ids)
            ->group('date')
            ->column('date');

        $new_arr = [];

        foreach ($date_arr as $k => $v) {
            $goodsList = Carts::getGoodsList($cart_ids, $user_id, 1, $v);
            array_push($new_arr, ['date' => $v, 'goods_list' => $goodsList]);
        }

        if (empty($goodsList)) {
            throw new \Exception("未找到商品");
        }

        $orderInfo['amount'] = 0;
        $orderInfo['goodsprice'] = 0;
        //$orderInfo['shippingfee'] = 0;
        $orderInfo['discount'] = 0;
        $orderInfo['coupon_money'] = 0;
        $orderItem = [];

        $userCoupon = null;
        $presentCoupon = 0;
        //校验领取和是否可使用
        if ($user_coupon_id) {
            $userCouponModel = new UserCoupon();
            $userCoupon = $userCouponModel->checkUserOrUse($user_coupon_id, $user_id);

            $coupon_info = \app\admin\model\shop\Coupon::get($userCoupon->coupon_id);
            if ($coupon_info->result==2){
                $presentCoupon = 1;
            }
            $orderInfo['user_coupon_id'] = $user_coupon_id;
        }
        $total_amount = 0;
        foreach ($new_arr as $k=>$v){
            $goodsList = $v['goods_list'];
            $order_amount = 0;
            $order_goodsprice = 0;
            $order_saleamount = 0;
            $order_discount = 0;
            //判断商品库存和状态
            foreach ($goodsList as $item) {
                $goodsItem = [];
                if (empty($item->goods) && empty($item->sku)) {
                    throw new \Exception("商品已下架");
                }
                //规格
                if ($item->goods_sku_id && empty($item->sku)) {
                    throw new \Exception("商品规格不存在");
                }

                if (!empty($item->sku)) { //规格计算
                    if ($item->sku->stocks < $item->nums) {
                        //throw new \Exception("有商品库存不足,请返回购物车重新修改");
                        throw new \Exception($item->goods->title."商品库存不足,请返回购物车重新修改");
                    }
                    $goodsItem['image'] = !empty($item->sku->image) ? $item->sku->image : $item->goods->image;

                    $goodsItem['marketprice'] = $item->sku->marketprice;
                    //$goodsItem['discountprice'] = $item->sku->discountprice;
                    $goodsItem['goods_sn'] = $item->sku->goods_sn;
                    $goodsItem['price'] = $item->sku->price;
                    $goodsprice = bcmul($item->sku->price, $item->nums, 2);
                    if ($user['level']==1){
                        $member_price =  $item->sku->price*$member_discount/10;
                        $item->sku->discountprice = $member_price;
                        $goodsItem['discountprice'] = $member_price;
                        $amount = bcmul($item->sku->discountprice, $item->nums, 2);
                        $discount_price = bcsub($item->sku->price,$item->sku->discountprice,2);
                        $order_discount = bcmul($discount_price, $item->nums, 2);
                    } else {
                        $order_discount = 0;
                        $item->sku->discountprice = $item->sku->price;
                        $goodsItem['discountprice'] = $item->sku->discountprice;
                        $amount = bcmul($item->sku->price, $item->nums, 2);
                    }
                } else { //商品默认计算
                    if ($item->goods->stocks < $item->nums) {
                        //throw new \Exception("有商品库存不足,请返回购物车重新修改");
                        throw new \Exception($item->goods->title."商品库存不足,请返回购物车重新修改");
                    }
                    $goodsItem['image'] = !empty($item->sku->image) ? $item->sku->image : $item->goods->image;
                    //$goodsItem['price'] = $item->goods->price;
                    $goodsItem['marketprice'] = $item->goods->marketprice;
                    //$goodsItem['discountprice'] = $item->goods->discountprice;
                    $goodsItem['goods_sn'] = $item->goods->goods_sn;
                    $goodsItem['price'] = $item->goods->price;
                    $goodsprice = bcmul($item->goods->price, $item->nums, 2);
                    if ($user['level']==1){
                        $member_price = $item->goods->price*$member_discount/10;
                        $goodsItem['discountprice'] = $member_price;
                        $item->goods->discountprice = $member_price;
                        $amount = bcmul($item->goods->discountprice, $item->nums, 2);
                        $discount_price = bcsub($item->goods->price,$item->goods->discountprice,2);
                        $order_discount = bcmul($discount_price, $item->nums, 2);
                    } else {
                        $order_discount = 0;
                        $item->goods->discountprice = $item->goods->price;
                        $goodsItem['discountprice'] = $item->goods->discountprice;
                        $amount = bcmul($item->goods->price, $item->nums, 2);
                    }

                }

                $goodsItem['goods_price'] = $goodsprice;
                $goodsItem['amount'] = $amount;
                $goodsItem['discount'] = $order_discount;

                //订单总价
                $orderInfo['amount'] = bcadd($orderInfo['amount'], $amount, 2);
                $order_amount = bcadd($order_amount, $amount, 2);
                $total_amount = bcadd($total_amount, $amount, 2);
                //商品总价-原价
                $orderInfo['goodsprice'] = bcadd($orderInfo['goodsprice'], $goodsprice, 2);
                $order_goodsprice = bcadd($order_goodsprice, $goodsprice, 2);

                $order_saleamount = $order_amount;
                //$order_saleamount = max(0, bcsub($order_amount, $order_discount, 2));
                $orderInfo['discount'] = bcadd($orderInfo['discount'], $order_discount, 2);
                //创建订单商品数据
                $orderItem[] = array_merge($goodsItem, [
                    'order_sn'     => $orderInfo['order_sn'],
                    'id'     => $item->id,
                    'goods_id'     => $item->goods_id,
                    'title'        => $item->goods->title,
                    'nums'         => $item->nums,
                    'goods_sku_id' => $item->goods_sku_id,
                    'attrdata'     => $item->sku_attr,
                    //'weight'       => $item->goods->weight,
                    'category_id'  => $item->goods->category_id,
                ]);
            }
            $discount = bcsub($order_goodsprice,$order_saleamount,2);
            $new_arr[$k]['goods_list'] = $goodsList;
            $new_arr[$k]['amount'] = bcadd($order_amount,$discount,2);
            $new_arr[$k]['goodsprice'] = $order_goodsprice;
            $new_arr[$k]['saleamount'] = $order_saleamount;
            $new_arr[$k]['discount'] = $discount;
            $new_arr[$k]['coupon_money'] = 0;
        }
        //订单总价(含邮费)
        //$orderInfo['amount'] = bcadd($orderInfo['goodsprice'], $orderInfo['shippingfee'], 2);
        //dump($userCoupon);die;
        //die;
        if (!empty($userCoupon)&&!$presentCoupon) {
            //校验优惠券
            $goods_ids = array_column($orderItem, 'goods_id');
            $category_ids = array_column($orderItem, 'category_id');
            $couponModel = new Coupon();
            $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
                ->checkCoupon()
                ->checkOpen()
                ->checkUseTime($userCoupon['createtime'])
                ->checkConditionGoods($goods_ids, $user_id, $category_ids);

            //计算折扣金额，判断是使用不含运费，还是含运费的金额
            list($new_money, $coupon_money) = $coupon->doBuy($total_amount,1);

            //判断优惠金额是否超出总价，超出则直接设定优惠金额为总价
            $orderInfo['coupon_money'] = $coupon_money > $total_amount ? $total_amount : $coupon_money;
        }

        if (!empty($userCoupon)) {
            $coupon = Coupon::get($userCoupon->coupon_id);
            $result = $coupon->result;

            //校验优惠券是折扣券用此方法算优惠
            if ($result==0){
                foreach ($new_arr as $k=>$v){
                    $couponModel = new Coupon();
                    $coupon = $couponModel->getCoupon($userCoupon['coupon_id'])
                        ->checkCoupon()
                        ->checkOpen();

                    //计算折扣金额，判断是使用不含运费，还是含运费的金额
                    list($new_money, $coupon_money) = $coupon->doBuy($v['saleamount']);
                    //dump($coupon_money);
                    //$coupon_favourable_money = $coupon_money > $order_saleamount ? $order_saleamount : $coupon_money;
                    //dump($coupon_favourable_money);
                    $coupon_favourable_money = $coupon_money;
                    $new_arr[$k]['coupon_money'] = $coupon_favourable_money;
                    $new_arr[$k]['saleamount'] = bcsub($v['saleamount'],$coupon_favourable_money, 2);

                }
            } elseif ($result==1){
                //满减用此优惠
                //$goodsList = $v['goods_list'];

                $coupon_money = $orderInfo['coupon_money'];
                $temp_goods_list = self::distributionGoodsCouponMoney($new_arr,$orderInfo['goodsprice'],$coupon_money);

                $new_arr = $temp_goods_list;
            } elseif ($result==2){
                //赠品
                $coupon_info = \app\admin\model\shop\Coupon::get($userCoupon->coupon_id);
                $goods_id = $coupon_info->goods_id;
                foreach ($new_arr as $k=>$v){
                    $goods_list = $v['goods_list'];
                    if ($v['date']==$date){
                        $cart_id = CartPresent::push($goods_id, $goods_sku_id, 1, $user_id,$date);
                        $goods_info = CartPresent::getGoodsInfo($cart_id,$user_id);
                        $goods_info['is_present'] = 1;
                        //创建订单商品数据
                        $orderItem[] = array_merge($goodsItem, [
                            'order_sn'     => $orderInfo['order_sn'],
                            'id'     => $goods_info['id'],
                            'goods_id'     => $goods_info['goods_id'],
                            'title'        => $goods_info['goods']['title'],
                            'nums'         => $goods_info['nums'],
                            'goods_sku_id' => $goods_info['goods_sku_id'],
                            'attrdata'     => $goods_info['sku_attr'],
                            'category_id'  => $goods_info['goods']['category_id'],
                            'price'        => 0,
                            'amount'        => 0,
                            'discount'        => 0,
                        ]);
                        array_push($goods_list,$goods_info);
                    }
                    $new_arr[$k]['goods_list'] = $goods_list;
                }

            }

        }
        //dump($new_arr);die;
        //die;
        //计算订单的应付金额【减去优惠券金额】
        $orderInfo['saleamount'] = max(0, bcsub($orderInfo['amount'], $orderInfo['coupon_money'], 2));
        //$orderInfo['saleamount'] = $orderInfo['amount'];
        $orderInfo['amount'] = bcadd($orderInfo['amount'], $orderInfo['discount'], 2);

        //$orderInfo['discount'] = bcadd($orderInfo['discount'], 0, 2);

        return [
            $orderItem,
            $new_arr,
            $userCoupon
        ];
    }

    /**
     * Notes:余额抵扣平均
     * User: gai
     * Date: 2023/11/1
     * Time: 15:13
     */
    /**
     * 按比例摊派优惠券优惠
     */
    public static function distributionGoodsCouponMoney($goods_list, $goods_money, $coupon_money)
    {
        $temp_coupon_money = $coupon_money;
        $last_key = count($goods_list) - 1;
        //dump($goods_list);die;
        foreach ($goods_list as $k => $v) {

            if ($last_key != $k) {
                $item_coupon_money = round(floor($v['goodsprice'] / $goods_money * $coupon_money * 100) / 100, 2);
            } else {
                $item_coupon_money = $temp_coupon_money;
            }
            $temp_coupon_money -= $item_coupon_money;
            $goods_list[$k]['coupon_money'] = $item_coupon_money;
            //dump($v['saleamount']);
            //dump($temp_coupon_money);
            $real_goods_money = $v['saleamount'] - $item_coupon_money;
            $real_goods_money = $real_goods_money < 0 ? 0 : $real_goods_money;

            $goods_list[$k]['saleamount'] = $real_goods_money;//真实订单项金额
        }
        return $goods_list;
    }

    /**
     * @ DateTime 2021-05-28
     * @ 创建订单
     * @param int    $address_id
     * @param int    $user_id
     * @param mixed  $cart_ids
     * @param string $memo
     * @return Order|null
     */
    public static function createOrder($community_id, $user_id, $cart_ids, $user_coupon_id, $memo,$receiver,$mobile,$shippingtime,$date,$goods_sku_id,$detail_address)
    {
        $community = \app\admin\model\Community::get($community_id);
        if (empty($community)) {
            throw new \Exception("小区不存在");
        }

        $order_timeout = \app\common\model\Config::get(['name'=>'order_timeout'])->value;

        $union_order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);

        $expiretime =  time() + $order_timeout*60;
        //订单主表
        $orderInfo = [
            'user_id'     => $user_id,
            'order_sn'    => $union_order_sn,
            'community_id'  => $community->id,
            'receiver'    => $receiver,
            'mobile'      => $mobile,
            'shippingtime'=>$shippingtime,
            'goodsprice'  => 0, //商品金额 (不含运费)
            'amount'      => 0, //总金额 (含运费)
            //'shippingfee' => 0, //运费
            'discount'    => 0, //优惠金额
            'saleamount'  => 0,
            'memo'        => $memo,
            'expiretime'  => $expiretime, //订单失效
            'status'      => 'normal',
            'address'=>$community->address,
        ];

        //订单详细表
        list($orderItem, $goodsList, $userCoupon) = self::computeCarts($orderInfo, $cart_ids, $user_id, $user_coupon_id,$date,$goods_sku_id);


        $order = null;
        Db::startTrans();
        try {

            $order_ids = [];
            //创建订单

            //减库存
            foreach ($goodsList as $k=>$v) {
                //dump($v);die;
                $order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
                $order_data = [
                    'user_id'=>$user_id,
                    'order_sn'=>$order_sn,
                    'date'=>$v['date'],
                    'goodsprice'=>$v['goodsprice'],
                    'amount'=>$v['amount'],
                    'saleamount'=>$v['saleamount'],
                    'discount'=>$v['discount'],
                    'memo'=>$orderInfo['memo'],
                    'status'=>$orderInfo['status'],
                    'community_id'=>$orderInfo['community_id'],
                    'receiver'=>$orderInfo['receiver'],
                    'mobile'=>$orderInfo['mobile'],
                    'shippingtime'=>$orderInfo['shippingtime'],
                    'coupon_money'=>$v['coupon_money'],
                    'address'=>$orderInfo['address'],
                    'expiretime'=>$orderInfo['expiretime'],
                    'detail_address' => $detail_address,
                ];

                $order = Order::create($order_data, true);
                //记录操作
                OrderAction::push($order_sn, '系统', '订单创建成功');
                array_push($order_ids,$order->id);
                $goods_list = $v['goods_list'];
                $newOrderItem = [];
                foreach ($goods_list as $item) {
                    if ($item->sku) {
                        $item->sku->setDec('stocks', $item->nums);
                    }
                    $item->goods->setDec("stocks", $item->nums);
                    foreach ($orderItem as $index => &$items){

                        if ($item->id==$items['id']){
                            array_push($newOrderItem,$items);
                        }
                    }
                }

                //计算单个商品折扣后的价格
                $saleamount = $order['saleamount'];
                $saleratio = bcdiv($saleamount, $order['goodsprice'], 10);
                $saleremains = $saleamount;
                //dump($saleratio);
                foreach ($newOrderItem as $index => &$item) {
                    //$newOrderItem[$index]['order_id'] = $order->id;
                    //dump(!isset($newOrderItem[$index + 1]));
                    if (!isset($newOrderItem[$index + 1])) {
                        $saleprice = $saleremains;
                        //dump($saleprice.'---');
                    } else {
                        $saleprice = $order['coupon_money'] == 0 ? $item['amount'] : bcmul(bcmul($item['price'], $item['nums'], 2), $saleratio, 2);
                        //dump($order['coupon_money']);
                        //$saleprice = $order['coupon_money'] == 0 ? bcdiv($item['amount'], $item['nums'], 2) : bcmul(bcmul($item['price'], $item['nums'], 2), $saleratio, 2);
                        //dump($item['price']);
                        //dump($item['nums']);
                        //dump($saleprice.'|||');
                    }
                    //dump($item);

                    $saleremains = bcsub($saleremains, $saleprice, 2);
                    $item['realprice'] = $saleprice;
                    $item['order_id'] = $order->id;
                    $item['order_sn'] = $order->order_sn;
                    unset($item['goods_price']);
                    unset($item['discountprice']);
                    //unset($item['order_sn']);
                    unset($item['amount']);
                    unset($item['discount']);
                    //unset($item['id']);
                    unset($item['category_id']);
                }

                unset($item);
                //dump($newOrderItem);
                //创建订单商品数据
                foreach ($newOrderItem as $index => $item) {
                    unset($item['id']);
                    OrderGoods::create($item, true);
                }
            }
            //die;
            $orderInfo['order_id'] = implode(',',$order_ids);

            unset($orderInfo['date']);
            //总单
            $orderUnion = OrderUnion::create($orderInfo);///-------

            //优惠券已使用
            if (!empty($userCoupon)) {
                $userCoupon->save(['is_used' => 2]);
            }

            $cron = new Crontab();
            $cron->setAttr('type','url');
            $cron->title = '订单到期关闭,订单编号:'.$union_order_sn;
            $cron->content = request()->domain().'/api/order/close?order_sn='.$union_order_sn;
            $cron->schedule = schedule($expiretime);
            $cron->maximums = 1;
            $cron->begintime = time();
            $cron->endtime = $expiretime;
            $cron->status = 'normal';
            $cron->save();

            //提交事务
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        //清空购物车
        Carts::clear($cart_ids);

        //订单应付金额为0时直接结算
        if ($orderUnion['saleamount'] == 0) {
            self::settle($orderUnion->order_sn, 0);
        }
        return $orderUnion;
    }


    /**
     * @ DateTime 2021-05-31
     * @ 订单信息
     * @param $order_sn
     * @param $user_id
     * @return array|false|\PDOStatement|string|Model
     */
    public static function getDetail($order_sn, $user_id)
    {
        return self::with(['orderGoods'])->where('order_sn', $order_sn)->where('user_id', $user_id)->find();
    }

    public static function getOrderDetail($order_sn, $user_id)
    {
        return self::where('order_sn', $order_sn)->where('user_id', $user_id)->find();
    }

    public static function getDeliveryDetail($order_sn, $deliverystaff_id)
    {
        return self::with(['orderGoods'])->where('order_sn', $order_sn)->where('deliverystaff_id', $deliverystaff_id)->find();
    }

    /**
     * @ 支付
     * @param string $orderid
     * @param int    $user_id
     * @param string $paytype
     * @param string $method
     * @param string $openid
     * @param string $notifyurl
     * @param string $returnurl
     * @return \addons\epay\library\Collection|\addons\epay\library\RedirectResponse|\addons\epay\library\Response|null
     * @throws \Exception
     */
    public static function pay($order_sn, $user_id, $paytype, $method = 'web', $openid = '', $notifyurl = null, $returnurl = null)
    {
        $request = \think\Request::instance();
        $order = self::getDetail($order_sn, $user_id);
        if (!$order) {
            throw new \Exception('订单不存在！');
        }
        if ($order->paystate) {
            throw new \Exception('订单已支付！');
        }
        if ($order->orderstate) {
            throw new \Exception('订单已失效！');
        }
        //支付金额为0，无需支付
        if ($order->saleamount == 0) {
            throw new \Exception('无需支付！');
        }
        $order_sn = $order->order_sn;
        // 启动事务
        Db::startTrans();
        try {
            //支付方式变更
            if (($order['method'] && $order['paytype'] == $paytype && $order['method'] != $method)) {
                $order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
                //更新电子面单
                $electronics = $order->order_electronics;
                foreach ($electronics as $aftersales) {
                    $aftersales->order_sn = $order_sn;
                    $aftersales->save();
                }
                //更新操作日志
                $orderAction = $order->order_action;
                foreach ($orderAction as $action) {
                    $action->order_sn = $order_sn;
                    $action->save();
                }
                $order->save(['order_sn' => $order_sn]);
                //更新订单明细
                foreach ($order->order_goods as $item) {
                    $item->order_sn = $order_sn;
                    $item->save();
                }
            }
            //更新支付类型和方法
            $order->save(['paytype' => $paytype, 'method' => $method]);
            //提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw new \Exception($e->getMessage());
        }
        $response = null;
        $epay = get_addon_info('epay');

        if ($epay && $epay['state']) {

            $notifyurl = $notifyurl ? $notifyurl : $request->root(true) . '/addons/shop/order/epay/type/notify/paytype/' . $paytype;
            $returnurl = $returnurl ? $returnurl : $request->root(true) . '/addons/shop/order/epay/type/return/paytype/' . $paytype . '/order_sn/' . $order_sn;

            //保证取出的金额一致，不一致将导致订单重复错误
            $amount = sprintf("%.2f", $order->saleamount);

            $params = [
                'amount'    => $amount,
                'orderid'   => $order_sn,
                'type'      => $paytype,
                'title'     => "支付{$amount}元",
                'notifyurl' => $notifyurl,
                'returnurl' => $returnurl,
                'method'    => $method,
                'openid'    => $openid
            ];
            try {
                $response = Service::submitOrder($params);
            } catch (GatewayException $e) {
                throw new \Exception(config('app_debug') ? $e->getMessage() : "支付失败，请稍后重试");
            }
        } else {
            throw new \Exception("请在后台安装配置微信支付宝整合插件");
        }
        return $response;
    }


    /**
     * 订单列表
     *
     * @param $param
     * @return \think\Paginator
     */
    public static function tableList($param)
    {
        $pageNum = 15;
        if (isset($param['num']) && !empty($param['num'])) {
            $pageNum = $param['num'];
        }

        return self::with(['orderGoods'=>function($query){//这里需要加上use（where需要的条件）
//            $query->where('salestate',0 );
        }])
            ->where(function ($query) use ($param) {
                $query->where('status', 'normal');
                //$query->where('order_goods.salestate', 0);

                if (isset($param['user_id']) && !empty($param['user_id'])) {
                    $query->where('user_id', $param['user_id']);
                }
                if (isset($param['id']) && !empty($param['id'])) {
                    $query->where('id','in',$param['id']);
                }
                if (isset($param['date']) && !empty($param['date'])) {

                    $query->where('date', $param['date']);
                }
                if (isset($param['orderstate']) && $param['orderstate'] != '') {
                    $query->where('orderstate', $param['orderstate']);
                }
                if (isset($param['shippingstate']) && $param['shippingstate'] != '') {
                    $query->where('shippingstate', $param['shippingstate']);
                }
                if (isset($param['paystate']) && $param['paystate'] != '') {
                    $query->where('paystate', $param['paystate']);
                }
                //$query->name('shop_order_goods')->where('salestate', '=',0);
                if (isset($param['q']) && $param['q'] != '') {
                    $query->where('order_sn', 'in', function ($query) use ($param) {
                        return $query->name('shop_order_goods')->where('order_sn|title', 'like', '%' . $param['q'] . '%')->field('order_sn');
                    });
                }
            })
            ->order('createtime desc')->paginate($pageNum, false, ['query' => request()->get()]);
    }

    /**
     * 订单列表
     *
     * @param $param
     * @return \think\Paginator
     */
    public static function newtableList($param)
    {
        return self::with(['orderGoods'])
            ->where(function ($query) use ($param) {
                $query->where('status', 'normal');

                if (isset($param['user_id']) && !empty($param['user_id'])) {
                    $query->where('user_id', $param['user_id']);
                }
                if (isset($param['id']) && !empty($param['id'])) {
                    $query->where('id','in',$param['id']);
                }
                if (isset($param['date']) && !empty($param['date'])) {
                    $query->where('date', $param['date']);
                }
                if (isset($param['orderstate']) && $param['orderstate'] != '') {
                    $query->where('orderstate', $param['orderstate']);
                }
                if (isset($param['shippingstate']) && $param['shippingstate'] != '') {
                    $query->where('shippingstate', $param['shippingstate']);
                }
                if (isset($param['paystate']) && $param['paystate'] != '') {
                    $query->where('paystate', $param['paystate']);
                }
                if (isset($param['q']) && $param['q'] != '') {
                    $query->where('order_sn', 'in', function ($query) use ($param) {
                        return $query->name('shop_order_goods')->where('order_sn|title', 'like', '%' . $param['q'] . '%')->field('order_sn');
                    });
                }
            })
            ->order('createtime desc')->select();
    }


    /**
     * @ DateTime 2021-06-01
     * @ 订单结算
     * @param string $order_sn      订单号
     * @param float  $payamount     支付金额
     * @param string $transactionid 流水号
     * @return bool
     */
    public static function settle($order_sn, $payamount, $transactionid = '',$paytype,$endtime)
    {
        $order = self::with(['orderGoods'])->where('order_sn', $order_sn)->find();
        if (!$order || $order->paystate == 1) {
            return false;
        }

        if ($payamount != $order->saleamount) {
            \think\Log::write("[shop][pay][{$order_sn}][订单支付金额不一致]");
            return false;
        }

        // 启动事务
        Db::startTrans();
        try {
            $order->paystate = 1;
            $order->transactionid = $transactionid;
            $order->payamount = $payamount;
            $order->paytime = time();
            $order->endtime = $endtime;
            $order->paytype = $paytype;

            $order->save();
            if ($order->payamount == $order->saleamount) {
                //支付完成后,商品销量+1
                foreach ($order->order_goods as $item) {
                    $goods = $item->goods;
                    $sku = $item->sku;
                    if ($goods) {
                        $goods->setInc('sales', $item->nums);
                    }
                    if ($sku) {
                        $sku->setInc('sales', $item->nums);
                    }
                }
            }
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
        //记录操作
        //OrderAction::push($order_sn, '系统', '订单支付成功');
        //发送通知
        return true;
    }

    public function editOrder($changeinfo,$addgoods,$user_id)
    {

        $data = $this->changeDetail($changeinfo,'',$addgoods,$user_id);
        $decrease_goods = $data['decrease_goods'];
        $add_goods_arr = $data['add_goods'];
        $cart_id_arr = $data['cart_id_arr'];
        //$changeinfo_arr = _json_decode($changeinfo,true);
        Db::startTrans();
        try {
            //减少餐品的数据处理
            foreach ($decrease_goods as $k=>$v){
                $order_detail = Order::get(['order_sn'=>$v['order_sn']]);
                $total_refund_price = 0;//总退款
                $total_goodsprice = 0;//总商品
                $total_discount = 0;

                foreach ($v['goods_list'] as $kk=>$vv){

                    $order_goods_detail = OrderGoods::get($vv['id']);
                    $nums = bcsub($order_goods_detail->nums,$vv['num'],2);//最开始的数量-删除的数量=现在的数量
                    //删减后的商品数量大于0,更改原始order_goods表的数据,否则就是删完了直接改状态
                    if ($nums>0){
                        $single_realprice = bcdiv($order_goods_detail->realprice,$order_goods_detail->nums,2);//金额÷数量=单个金额
                        $order_goods_detail->nums = $nums;
                        $order_goods_detail->realprice = bcdiv($single_realprice,$nums,2);//单个金额*现有得数量
                        $order_goods_detail->save();

                        $order_goods_model = new OrderGoods();
                        $order_goods_data = [
                            'order_sn'=>$v['order_sn'],
                            'order_id'=>$order_detail->id,
                            'goods_id'=>$vv['goods_id'],
                            'goods_sku_id'=>$vv['goods_sku_id'],
                            'title'=>$vv['title'],
                            'nums'=>$vv['num'],
                            'marketprice'=>$vv['marketprice'],
                            'price'=>$vv['price'],
                            'realprice'=>$vv['refund_price'],
                            'attrdata'=>$vv['attrdata'],
                            'image'=>$vv['image'],
                            'salestate'=>4
                        ];
                        $order_goods_model->save($order_goods_data);
                        $refund_price = $vv['refund_price'];
                        $goodsprice = bcdiv($vv['price'],$vv['num'],2);
                        $discount = bcsub($goodsprice,$refund_price,2);
                    } else {
                        $order_goods_detail->salestate=4;
                        $refund_price = $order_goods_detail->realprice;
                        $goodsprice = bcdiv($order_goods_detail->price,$order_goods_detail->nums,2);
                        $discount = bcsub($goodsprice,$refund_price,2);
                    }

                    $order_goods_detail->save();
                    $total_refund_price+=$refund_price;
                    $total_goodsprice+=$goodsprice;
                    $total_discount+=$discount;
                    //执行同步退款
                    if($order_detail->paytype=='balance'){
                        //余额
                        \app\common\model\User::money($refund_price,$order_detail->user_id,'减少餐品:'.$vv['title'].',退款:'.$refund_price);
                    } else {
                        //微信
                        \app\admin\model\shop\Order::refund($order_detail->order_sn,'wechat', $refund_price);
                    }
                }
                if ($order_detail->payamount==$total_refund_price){
                    //减少餐品的金额==付款金额相当于该订单取消
                    $order_detail->orderstate = 1;
                    $order_detail->canceltime = time();
                } else{
                    //修改原始的订单的付款金额等信息
                    $order_detail->saleamount-=$total_refund_price;
                    $order_detail->payamount-=$total_refund_price;
                    $order_detail->goodsprice-=$total_goodsprice;
                    $order_detail->discount-=$total_discount;
                }
                $order_detail->save();
            }


            //新增餐品的处理

            $union_order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
            //订单主表
            $orderInfo = [
                'user_id'     => $user_id,
                'order_sn'    => $union_order_sn,
                'order_id'    => []
            ];
            $total_goodsprice = 0;
            $total_amount = 0;
            $total_saleamount = 0;
            $total_discount = 0;
            foreach ($add_goods_arr as $k=>$v){
                $order = Order::get(['order_sn'=>$v['order_sn']]);


                $card_id = array_column($v['goods_list'],'id');

                list($orderItem, $goodsList) = self::computeNewAdd($orderInfo, $card_id, $user_id,$v['order_sn']);

                $order_ids = [];
                //减库存
                foreach ($goodsList as $kk=>$vv) {
                    $total_goodsprice+=$vv['goodsprice'];
                    $total_saleamount+=$vv['saleamount'];
                    $total_amount+=$vv['amount'];
                    $total_discount+=$vv['discount'];
                    $order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
                    $order_data = [
                        'user_id'=>$user_id,
                        'order_sn'=>$order_sn,
                        'goodsprice'=>$vv['goodsprice'],
                        'amount'=>$vv['amount'],
                        'saleamount'=>$vv['saleamount'],
                        'discount'=>$vv['discount'],
                        'parent_order_id'=>$order->id
                    ];

                    $order = OrderAdd::create($order_data, true);
                    //记录操作
                    OrderAction::push($order_sn, '系统', '新增订单创建成功');
                    array_push($order_ids,$order->id);
                    $goods_list = $v['goods_list'];
                    $newOrderItem = [];
                    foreach ($goods_list as $item) {
                        if ($item->sku) {
                            $item->sku->setDec('stocks', $item->nums);
                        }
                        $item->goods->setDec("stocks", $item->nums);
                        foreach ($orderItem as $index => &$items){

                            if ($item->id==$items['id']){
                                array_push($newOrderItem,$items);
                            }
                        }
                    }

                    //计算单个商品折扣后的价格
                    $saleamount = $order['saleamount'];
                    $saleratio = bcdiv($saleamount, $order['goodsprice'], 10);
                    $saleremains = $saleamount;

                    foreach ($newOrderItem as $index => &$item) {

                        if (!isset($newOrderItem[$index + 1])) {
                            $saleprice = $saleremains;

                        } else {
                            $saleprice = $order['discount'] == 0 ? $item['amount'] : bcmul(bcmul($item['price'], $item['nums'], 2), $saleratio, 2);

                        }

                        $saleremains = bcsub($saleremains, $saleprice, 2);
                        $item['realprice'] = $saleprice;
                        $item['order_id'] = $order->id;
                        $item['order_sn'] = $order->order_sn;
                        unset($item['goods_price']);
                        unset($item['discountprice']);
                        //unset($item['order_sn']);
                        unset($item['amount']);
                        unset($item['discount']);
                        //unset($item['id']);
                        unset($item['category_id']);
                    }

                    unset($item);
                    //dump($newOrderItem);
                    //创建订单商品数据
                    foreach ($newOrderItem as $index => $item) {
                        unset($item['id']);
                        OrderGoodsAdd::create($item, true);
                    }
                }
                array_push($orderInfo['order_id'],implode(',',$order_ids));
                //die;
                //$orderInfo['order_id'] = implode(',',$order_ids);

                unset($orderInfo['date']);
                //总单
                //$orderUnion = OrderUnionAdd::create($orderInfo);///-------

                //清空购物车
                Carts::clear($card_id);

            }
            $orderInfo['order_id'] = implode(',',$orderInfo['order_id']);
            $orderInfo['goodsprice'] = $total_goodsprice;
            $orderInfo['amount'] = $total_amount;
            $orderInfo['saleamount'] = $total_saleamount;
            $orderInfo['discount'] = $total_discount;
            $orderUnion = OrderUnionAdd::create($orderInfo);

            Db::commit();
            return $orderUnion;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage().$e->getLine());
        }

    }

    //修改订单的减少餐品信息
    public function changeDetail($changeinfo,$order_sn='',$addgoods,$user_id)
    {
        $decrease_goods = [];//减少商品

        $search_arr = [];//当前订单的信息

        //$change_goods = [];//变化后的商品
        $change_goods = OrderGoods::where(['order_sn'=>$order_sn])->where('salestate',0)->select();

        $total_refund_price = 0;
        $total_pay_price = 0;
        $changeinfo_arr = _json_decode($changeinfo,true);
        if (count($changeinfo_arr)>0){

            foreach ($changeinfo_arr as $k=>$v){
                if ($v['order_sn']==$order_sn){
                    $search_arr = $v;
                }
                $order = Order::get(['order_sn'=>$v['order_sn']]);
                $date = $order->date;
                $refund_price = 0;
                $goods_list = [];
                foreach ($v['order_goods'] as $kk=>$vv){
                    $order_goods = OrderGoods::where(['id'=>$vv['order_goods_id']])->find();

                    //减少商品
                    $decrease_goods_data = [
                        'id'=>$order_goods['id'],
                        'order_sn'=>$order_goods['order_sn'],
                        'goods_id'=>$order_goods['goods_id'],
                        'goods_sku_id'=>$order_goods['goods_sku_id'],
                        'title'=>$order_goods['title'],
                        'num'=>$vv['num'],
                        'marketprice'=>$order_goods['marketprice'],
                        'price'=>$order_goods['price'],
                        'realprice'=>$order_goods['realprice'],
                        'attrdata'=>$order_goods['attrdata'],
                        'image'=>$order_goods['image'],
                        'refund_price'=>$order_goods['realprice']/$order_goods['nums']*$vv['num']
                    ];
                    $refund_price+=$decrease_goods_data['refund_price'];
                    $total_refund_price+=$decrease_goods_data['refund_price'];
                    array_push($goods_list,$decrease_goods_data);
                }
                array_push($decrease_goods,[
                    'date'=>$date,
                    'order_sn'=>$v['order_sn'],
                    'refund_price'=>$refund_price,
                    'goods_list'=>$goods_list,
                ]);
            }
        }

        if ($order_sn&&count($search_arr)>0){
            //dump($search_arr);die;
            foreach ($search_arr['order_goods'] as $k=>$v){
                $order_goods = OrderGoods::where(['id'=>$v['order_goods_id']])->find();
                foreach ($change_goods as $kk=>$vv){
                    if ($vv['id']==$v['order_goods_id'])unset($change_goods[$kk]);

                }
                if ($order_goods['nums']-$v['num']>0){
                    $change_goods_data = [
                        'id'=>$order_goods['id'],
                        'order_sn'=>$order_goods['order_sn'],
                        'goods_id'=>$order_goods['goods_id'],
                        'goods_sku_id'=>$order_goods['goods_sku_id'],
                        'title'=>$order_goods['title'],
                        'nums'=>$order_goods['nums']-$v['num'],
                        'marketprice'=>$order_goods['marketprice'],
                        'price'=>$order_goods['price'],
                        'realprice'=>$order_goods['realprice']/$order_goods['nums']*($order_goods['nums']-$v['num']),
                        'attrdata'=>$order_goods['attrdata'],
                        'image'=>$order_goods['image'],
                    ];
                    array_push($change_goods,$change_goods_data);
                }

            }
        }

        $add_goods = [];//新增的商品
        $cart_id_arr = [];
        $addgoods_arr = _json_decode($addgoods,true);

        foreach ($addgoods_arr as $k=>$v){
            $order = Order::get(['order_sn'=>$v['order_sn']]);
            $date = $order->date;
            $cart_ids = [];//单个订单的购物车id
            foreach ($v['goods_list'] as $kk=>$vv){
                $row = Carts::where('goods_id', $vv['goods_id'])
                    ->where('goods_sku_id', $vv['goods_sku_id'])
                    ->where('user_id', $user_id)
                    ->where('order_id', $order->id)
                    ->where('sceneval', 3)
                    ->where('date', $date)
                    ->find();
                if (!$row){
                    $row = new Carts();
                    $row->save([
                        'goods_id'     => $vv['goods_id'],
                        'goods_sku_id' => $vv['goods_sku_id'],
                        'user_id'      => $user_id,
                        'sceneval'     => 3,
                        'nums'         => $vv['nums'],
                        'date'         => $date,
                        'order_id'     => $order->id
                    ]);
                }
                array_push($cart_ids,$row->id);
                array_push($cart_id_arr,$row->id);
            }
            $orderInfo = [];
            list($orderItem, $goodsList) = self::computeNewAdd($orderInfo, $cart_ids,$user_id,$v['order_sn']);
            foreach ($goodsList as $kk=>$vv){
                $total_pay_price+=$vv['saleamount'];
            }

            $add_goods=array_merge($add_goods,$goodsList);
        }

        $data = [
            'change_goods'=>array_values($change_goods),
            'decrease_goods'=>$decrease_goods,
            'add_goods'=>$add_goods,
            'cart_id_arr'=>$cart_id_arr,
            'total_refund_price'=>$total_refund_price,
            'total_pay_price'=>$total_pay_price
        ];

        return $data;
    }


    public static function newCreateOrder($user_id, $cart_ids,$order_sn)
    {

        $union_order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
        //订单主表
        $orderInfo = [
            'user_id'     => $user_id,
            'order_sn'    => $union_order_sn,
            'goodsprice'  => 0, //商品金额 (不含运费)
            'amount'      => 0, //总金额 (含运费)
            'discount'    => 0, //优惠金额
            'saleamount'  => 0,
        ];

        //订单详细表
        list($orderItem, $goodsList) = self::computeNewAdd($orderInfo, $cart_ids, $user_id,'');


        $order = null;
        Db::startTrans();
        try {

            $order_ids = [];
            //创建订单

            //减库存
            foreach ($goodsList as $k=>$v) {
                //dump($v);die;
                $order_sn = date("Ymdhis") . sprintf("%08d", $user_id) . mt_rand(1000, 9999);
                $order_data = [
                    'user_id'=>$user_id,
                    'order_sn'=>$order_sn,
                    'date'=>$v['date'],
                    'goodsprice'=>$v['goodsprice'],
                    'amount'=>$v['amount'],
                    'saleamount'=>$v['saleamount'],
                    'discount'=>$v['discount'],
                ];

                $order = OrderAdd::create($order_data, true);
                //记录操作
                OrderAction::push($order_sn, '系统', '新增订单创建成功');
                array_push($order_ids,$order->id);
                $goods_list = $v['goods_list'];
                $newOrderItem = [];
                foreach ($goods_list as $item) {
                    if ($item->sku) {
                        $item->sku->setDec('stocks', $item->nums);
                    }
                    $item->goods->setDec("stocks", $item->nums);
                    foreach ($orderItem as $index => &$items){

                        if ($item->id==$items['id']){
                            array_push($newOrderItem,$items);
                        }
                    }
                }

                //计算单个商品折扣后的价格
                $saleamount = $order['saleamount'];
                $saleratio = bcdiv($saleamount, $order['goodsprice'], 10);
                $saleremains = $saleamount;

                foreach ($newOrderItem as $index => &$item) {

                    if (!isset($newOrderItem[$index + 1])) {
                        $saleprice = $saleremains;

                    } else {
                        $saleprice = $order['discount'] == 0 ? $item['amount'] : bcmul(bcmul($item['price'], $item['nums'], 2), $saleratio, 2);

                    }

                    $saleremains = bcsub($saleremains, $saleprice, 2);
                    $item['realprice'] = $saleprice;
                    $item['order_id'] = $order->id;
                    $item['order_sn'] = $order->order_sn;
                    unset($item['goods_price']);
                    unset($item['discountprice']);
                    //unset($item['order_sn']);
                    unset($item['amount']);
                    unset($item['discount']);
                    //unset($item['id']);
                    unset($item['category_id']);
                }

                unset($item);
                //dump($newOrderItem);
                //创建订单商品数据
                foreach ($newOrderItem as $index => $item) {
                    unset($item['id']);
                    OrderGoodsAdd::create($item, true);
                }
            }
            //die;
            $orderInfo['order_id'] = implode(',',$order_ids);

            unset($orderInfo['date']);
            //总单
            $orderUnion = OrderUnionAdd::create($orderInfo);///-------


            //提交事务
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw new Exception($e->getMessage());
        }
        //清空购物车
        Carts::clear($cart_ids);

        return $orderUnion;
    }

    //计算新增商品的信息
    public static function computeNewAdd(&$orderInfo, $cart_ids, $user_id,$order_sn)
    {
        $user = User::get($user_id);
        $member_discount = \app\common\model\Config::get(['name'=>'member_discount'])->value;
        $date_arr = Carts::where(['user_id'=>$user_id])
            ->where('id','in',$cart_ids)
            ->group('date')
            ->column('date');

        $new_arr = [];

        foreach ($date_arr as $k => $v) {
            $goodsList = Carts::getGoodsList($cart_ids, $user_id, 3, $v);
            array_push($new_arr, ['date' => $v,'order_sn'=>$order_sn, 'goods_list' => $goodsList]);
        }

        if (empty($goodsList)) {
            throw new \Exception("未找到商品");
        }

        $orderInfo['amount'] = 0;
        $orderInfo['goodsprice'] = 0;
        $orderInfo['discount'] = 0;

        $orderItem = [];

        $total_amount = 0;
        foreach ($new_arr as $k=>$v){
            $goodsList = $v['goods_list'];
            $order_amount = 0;
            $order_goodsprice = 0;
            $order_saleamount = 0;
            $order_discount = 0;
            //判断商品库存和状态
            foreach ($goodsList as $item) {
                $goodsItem = [];
                if (empty($item->goods) && empty($item->sku)) {
                    throw new \Exception("商品已下架");
                }
                //规格
                if ($item->goods_sku_id && empty($item->sku)) {
                    throw new \Exception("商品规格不存在");
                }

                if (!empty($item->sku)) { //规格计算
                    if ($item->sku->stocks < $item->nums) {
                        throw new \Exception("有商品库存不足,请返回购物车重新修改");
                    }
                    $goodsItem['image'] = !empty($item->sku->image) ? $item->sku->image : $item->goods->image;

                    $goodsItem['marketprice'] = $item->sku->marketprice;
                    //$goodsItem['discountprice'] = $item->sku->discountprice;
                    $goodsItem['goods_sn'] = $item->sku->goods_sn;
                    $goodsItem['price'] = $item->sku->price;
                    $goodsprice = bcmul($item->sku->price, $item->nums, 2);
                    if ($user['level']==1){
                        $member_price =  $item->sku->price*$member_discount/10;
                        $item->sku->discountprice = $member_price;
                        $goodsItem['discountprice'] = $member_price;
                        $amount = bcmul($item->sku->discountprice, $item->nums, 2);
                        $discount_price = bcsub($item->sku->price,$item->sku->discountprice,2);
                        $order_discount = bcmul($discount_price, $item->nums, 2);
                    } else {
                        $order_discount = 0;
                        $item->sku->discountprice = $item->sku->price;
                        $goodsItem['discountprice'] = $item->sku->discountprice;
                        $amount = bcmul($item->sku->price, $item->nums, 2);
                    }
                } else { //商品默认计算
                    if ($item->goods->stocks < $item->nums) {
                        throw new \Exception("有商品库存不足,请返回购物车重新修改");
                    }
                    $goodsItem['image'] = !empty($item->sku->image) ? $item->sku->image : $item->goods->image;
                    //$goodsItem['price'] = $item->goods->price;
                    $goodsItem['marketprice'] = $item->goods->marketprice;
                    //$goodsItem['discountprice'] = $item->goods->discountprice;
                    $goodsItem['goods_sn'] = $item->goods->goods_sn;
                    $goodsItem['price'] = $item->goods->price;
                    $goodsprice = bcmul($item->goods->price, $item->nums, 2);
                    if ($user['level']==1){
                        $member_price = $item->goods->price*$member_discount/10;
                        $goodsItem['discountprice'] = $member_price;
                        $item->goods->discountprice = $member_price;
                        $amount = bcmul($item->goods->discountprice, $item->nums, 2);
                        $discount_price = bcsub($item->goods->price,$item->goods->discountprice,2);
                        $order_discount = bcmul($discount_price, $item->nums, 2);
                    } else {
                        $order_discount = 0;
                        $item->goods->discountprice = $item->goods->price;
                        $goodsItem['discountprice'] = $item->goods->discountprice;
                        $amount = bcmul($item->goods->price, $item->nums, 2);
                    }

                }

                $goodsItem['goods_price'] = $goodsprice;
                $goodsItem['amount'] = $amount;
                $goodsItem['discount'] = $order_discount;



                //订单总价
                $orderInfo['amount'] = bcadd($orderInfo['amount'], $amount, 2);
                $order_amount = bcadd($order_amount, $amount, 2);
                $total_amount = bcadd($total_amount, $amount, 2);
                //商品总价-原价
                $orderInfo['goodsprice'] = bcadd($orderInfo['goodsprice'], $goodsprice, 2);
                $order_goodsprice = bcadd($order_goodsprice, $goodsprice, 2);

                $order_saleamount = $order_amount;
                //$order_saleamount = max(0, bcsub($order_amount, $order_discount, 2));
                $orderInfo['discount'] = bcadd($orderInfo['discount'], $order_discount, 2);
                //创建订单商品数据
                $orderItem[] = array_merge($goodsItem, [
                    //'order_sn'     => $orderInfo['order_sn'],
                    'id'     => $item->id,
                    'goods_id'     => $item->goods_id,
                    'title'        => $item->goods->title,
                    'nums'         => $item->nums,
                    'goods_sku_id' => $item->goods_sku_id,
                    'attrdata'     => $item->sku_attr,
                    //'weight'       => $item->goods->weight,
                    'category_id'  => $item->goods->category_id,
                ]);
            }
            $discount = bcsub($order_goodsprice,$order_saleamount,2);
            $new_arr[$k]['goods_list'] = $goodsList;
            $new_arr[$k]['amount'] = bcadd($order_amount,$discount,2);
            $new_arr[$k]['goodsprice'] = $order_goodsprice;
            $new_arr[$k]['saleamount'] = $order_saleamount;
            $new_arr[$k]['discount'] = $discount;
        }
        //订单总价(含邮费)

        //计算订单的应付金额【减去优惠券金额】

        $orderInfo['saleamount'] = $orderInfo['amount'];
        $orderInfo['amount'] = bcadd($orderInfo['amount'], $orderInfo['discount'], 2);

        return [
            $orderItem,
            $new_arr
        ];
    }

    public function user()
    {
        return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function orderGoods()
    {
        return $this->hasMany('OrderGoods', 'order_sn', 'order_sn');
    }


    public function orderAction()
    {
        return $this->hasMany('OrderAction', 'order_sn', 'order_sn');
    }
}
